package com.qpx.studentservice.aop;


import com.alibaba.fastjson.JSON;
import com.qpx.logmongodb.eneity.LogEntity;
import com.qpx.studentservice.annotation.Log;
import com.qpx.studentservice.service.LogService;
import com.qpx.studentservice.vo.ResultEntity;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;

@Component
@Aspect
@Slf4j
public class LogAop {


    @Autowired
    LogService logService;

    @Pointcut(value="execution(* com.qpx.studentservice.web.*.*(..))")
    public void pointcut(){}


    @AfterReturning(pointcut="pointcut()")
    public void after(JoinPoint joinPoint){
        Method method = ((MethodSignature)joinPoint.getSignature()).getMethod();
        Log annotation = method.getAnnotation(Log.class);
        if (annotation!=null){
            ServletRequestAttributes requestAttributes = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes());
            HttpServletRequest request = requestAttributes.getRequest();
            LogEntity logEntity = new LogEntity();
            logEntity.setPort(request.getServerPort()+"");
            logEntity.setDesc(annotation.value());
            logEntity.setIp(request.getRemoteAddr());
            logEntity.setMethod(request.getMethod());
            logEntity.setUrl(request.getRequestURI());
            logEntity.setMenthodName(method.getName());
            ResultEntity add = logService.add(logEntity);
            log.info("------------------------------->{}", JSON.toJSONString(add));

        }
    }


}
